import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router';
import { routes } from './routes';
import { useRouteStore } from '@/store/routes';
// 页面跳转时的进度条
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
import { post } from "@/service/request";

NProgress.configure({
    easing: 'ease', // 动画方式,
    speed: 500, // 递增进度条的速度,
    showSpinner: false, // 是否显示加载icon,
    trickleSpeed: 200, // 自动递增间隔,
    minimum: 0.3, // 初始化最小百分比
})
const router = createRouter({
    history: createWebHistory(),
    // history: createWebHashHistory(),
    routes
})

// 前端埋点获取页面浏览事件
let startTime = dayjs();
let startTimeFormat = startTime.format('YYYY-MM-DD hh:mm:ss');
const getUserInfo = (to: any, from: any, token: any) => {
    // 获取当前时间
    let currentTime = dayjs();
    let currentTimeFormat = currentTime.format('YYYY-MM-DD hh:mm:ss');
    let brow_history = {
        preUrl: from.path,
        preTitle: from.meta.title,
        currentUrl: to.path,
        currentTitle: to.meta.title,
        prePage_browTime: currentTime.diff(startTime, 'second') + 's',
        user: JSON.parse(token),
    }
    // console.log('用户由', JSON.parse(token).info.id, JSON.parse(token).info.name, to.meta?.pointName, ' 页面停留了 ', currentTimeFormat + '秒');
    if (to.meta?.pointName) {
        setUserBrowInfo(token, currentTimeFormat, to.meta.pointName);
    }
}

// 统计用户浏览信息
function setUserBrowInfo(token: any, createDate: any, content: any) {
    let browParam = {
        content: content,
        createDate: createDate,
        creatorId: JSON.parse(token).info.id,
        creator: JSON.parse(token).info.name,
    }
    console.log('abc', browParam);
    post(`/operator/save`, browParam).then((res: any) => {
        if (res.errCode == 0) {
            console.log('埋点成功');
        } else {
            console.log('===暂不处理===', res.msg);
        }
    });
}
router.beforeEach((to, from, next) => {
    const routeStore = useRouteStore();

    // 每次切换页面时，调用进度条
    const token = localStorage.getItem('user');

    if (token) {
        getUserInfo(to, from, token);
        next();
    } else {
        console.log('================未登录=====================');
    }
    NProgress.start();
    if (to.meta.menuKey != undefined) {
        routeStore.addRoute(to);
        routeStore.setRouterTagActive(to);
    }
    next()
})

router.afterEach(() => {
    NProgress.done();
})
export default router;